<script lang="ts" setup>

import axios from 'axios';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'

let form = ref({
    username:"",
    password:"",
})
let router = useRouter()
async function onSubmit(){
  try {
      const res = await axios.post("http://localhost:8080/api/auth/login",form.value,
        {
          headers: {
            'Content-Type': 'application/json'
        }
  }
      )
      localStorage.setItem("token",res.data.data.token)
      localStorage.setItem("username",res.data.data.username)
      localStorage.setItem("userId",res.data.data.userId)
      console.log(res.data)
      ElMessage({
          message: res.data.message,
          type: 'success',
        })
      router.replace("/Books")
    // 成功处理逻辑
  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error('登录失败，请检查用户名和密码');
  }
}

function onRegister(){
    router.push("/register")
}

</script>

<template>
    <h1>图书登录</h1>
    <div class="login-container">
      <el-form :model="form" label-width="60px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password" type="password" placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <el-button @click="onRegister">注册</el-button>
          </el-form-item>
      </el-form>
    </div>
    
</template>

<style lang="css" scoped>
    .login-container {
      display: flex;
      justify-content: center;
      align-items: center; 
      height: 50vh; 
      //border: 2px solid black;
    }
    h1{
      text-align: center;
    }
</style>